package com.accenture.portal.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginViewInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
			//request.getRequestDispatcher("login.action?user_id=" + user_id + "&user_password=" + user_password).forward(request, response);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		String user_id = null;
		String user_password = null;
		
		Cookie[] cookies = request.getCookies();

		for (Cookie cookie: cookies) {
			if (cookie.getName().equals("user_id_cookie")) {
				user_id = cookie.getValue();
			}
			if (cookie.getName().equals("user_password_cookie")) {
				user_password = cookie.getValue();
			}
		}
		
		//System.out.println(user_id + "-" + user_password);
		
		if (user_id == null || user_password == null) {
			//true -> continue
			return true;
		} else {
			request.getRequestDispatcher("login.action?user_id=" + user_id + "&user_password=" + user_password).forward(request, response);
			//false -> stay
			return false;
		}
		
	}
}
